<template>
  <page-header class="mt-18px mb-15px" :count="count" :title="title" :menuId="menuId" is-small />
  <div class="filter-wrapper">
    <vc-filter :menus="menus" />
    <div class="filters">
      <div class="source">
        <span>溯源</span>
        <el-switch v-model="traceSource" size="small" style="--el-switch-on-color: #02C680" />
      </div>
      <div class="total-num">
        共计
        <sapn style="color: rgba(255, 89, 89, 1)">{{ totalNum }}</sapn>
        条
      </div>
    </div>
  </div>

  <vc-table
    v-show="!_noData"
    :loading="loading"
    :tableData="tableData"
    :columns="columns"
    :total="totalNum"
    :pageSize="queryData.pageSize"
    v-model:pageNum="queryData.pageNum"
    :defaultSort="{ field: '300211', order: 'desc' }"
    @page-change="handleCurrentChange"
    @sort-change="sortChange"
  />
  <vc-nodata v-show="_noData" :type="203"></vc-nodata>

  <indicator-source v-model:show="showActionsheet" :actionData="actionSheetData" />
</template>

<script setup lang="tsx">
import PageHeader from '../../../../components/page-header.vue';
import indicatorSource from '@/components/indicator-source/index.vue';
import { useScreen } from './useScreen';
import { useTable } from './useTable';
import { getEnvironmentalPerformanceFilter, getCurrencyCode, getComparison } from '../../../../apis';
import { COMPANY_NAME } from '@/utils';
import { useF9Context } from '@/views/modules/enterprise/use/use-context';

interface Props {
  title: string;
  menuId: string;
  count?: number;
}

const _noData = ref(false);

const { title, menuId, count } = defineProps<Props>();

const { companyId } = useF9Context();

const { queryData, menus, traceSource } = useScreen();

const { totalNum, tableData, columns } = useTable();
const showActionsheet = ref(false);
const actionSheetData = ref();

const loading = ref(false);

const indicators = reactive({
  allPurpose: [],
  commonSense: {},
  industryFilterList: []
});

const isFirstLoad = ref(true);
const isPageChange = ref(false);
watch(
  () => queryData,
  (val) => {
    if (isFirstLoad.value) {
      if (val.industryCode && val.statisticalPeriod && val.currencyType) {
        isFirstLoad.value = false;
        getData();
      }
    } else {
      if (!isPageChange.value) {
        queryData.pageNum = 1;
      } else {
        isPageChange.value = false;
      }
      getData();
    }
  },
  { deep: true }
);

const initData = async () => {
  queryData.companyId = companyId;
  const res = await Promise.all([getEnvironmentalPerformanceFilter(companyId), getCurrencyCode()]);
  indicators.allPurpose = res[0].allPurpose;
  indicators.commonSense = res[0].commonSense;
  indicators.industryFilterList = res[0].industryFilterList;
  menus.value[0].options = res[0].industryFilterList;
  queryData.industryCode = res[0].industryFilterList[0].code;
  queryData.indicatorType = res[0].industryFilterList[0].indicatorType;
  queryData.industryCategoryType = res[0].industryFilterList[0].industryType;
  queryData.name = res[0].industryFilterList[0].name;
  menus.value[0].value = queryData.industryCode;
  menus.value[0].submitFn = (val: string) => {
    queryData.industryCode = val;
    const item = indicators.industryFilterList?.find((o: any) => o.code === val) as any;
    queryData.indicatorType = item?.indicatorType;
    queryData.industryCategoryType = item?.industryType;
    queryData.name = item?.name;
    if (item?.indicatorType === 'commonSense') {
      menus.value[2].options = indicators.commonSense[item?.code];
    } else {
      menus.value[2].options = indicators.allPurpose;
    }
  };
  menus.value[1].options = res[0].years.map((y) => {
    return { name: y.year + '年', code: y.year + '' };
  });
  queryData.statisticalPeriod = res[0].years.find((o) => o.active == true).year + '';
  menus.value[1].value = queryData.statisticalPeriod;
  menus.value[1].submitFn = (val: string) => {
    queryData.statisticalPeriod = val;
  };
  if (res[0].industryFilterList[0].indicatorType === 'commonSense') {
    menus.value[2].options = res[0].commonSense[res[0].industryFilterList[0].code];
  } else {
    menus.value[2].options = res[0].allPurpose;
  }
  menus.value[2].submitFn = (val: any) => {
    const { lv1, lv2, lv3 } = val;
    let tree = {
      options_1: lv1 || [],
      options_2: lv2 || [],
      options_3: lv3 || []
    };
    const { indicatorCodes } = useTransferIndicatorParams(tree, menus.value[2].options);
    queryData.indicatorCodes = indicatorCodes;
  };
  menus.value[3].options = res[1];
  queryData.currencyType = res[1][0].code;
  menus.value[3].value = queryData.currencyType;
  menus.value[3].submitFn = (val: string) => {
    queryData.currencyType = val;
  };

  getData();
};

initData();

const useTransferIndicatorParams = (tree: any, list: Array<any>) => {
  let arr: Array<string> = [];
  if (tree.options_2.length === 0) {
    arr = tree.options_1;
  } else if (tree.options_2.length > 0 && tree.options_3.length === 0) {
    arr = tree.options_2;
  } else if (tree.options_3.length > 0) {
    const lv2HasLv3Codes: Array<string> = [];
    list.forEach((lv1: any) => {
      lv1.values.forEach((lv2: any) => {
        if (lv2.values.length) {
          lv2HasLv3Codes.push(lv2.code);
        }
      });
    });
    arr = [...tree.options_2.filter((code: string) => !lv2HasLv3Codes.includes(code)), ...tree.options_3];
  }
  return {
    indicatorCodes: arr.join()
  };
};

const getData = async () => {
  loading.value = true;
  const res = await getComparison(queryData);
  loading.value = false;
  if (res?.comparisonData?.indicators?.length) {
    _noData.value = false;
  } else {
    _noData.value = true;
  }
  const { _columns, _data } = handleRes(res);
  columns.value = [
    ...[
      {
        field: 'seqIndex',
        title: '序号',
        width: 70,
        fixed: 'left',
        align: 'center',
        slots: {
          default: ({ row }) => {
            return row.seqIndex ? row.seqIndex : '-';
          }
        }
      },
      { ...COMPANY_NAME }
    ],
    ..._columns
  ];
  totalNum.value = res.comparisonData.total;
  tableData.value = _data;
};

const handleCurrentChange = (page: number) => {
  queryData.pageNum = page;
  isPageChange.value = true;
};

const sortChange = (event: any) => {
  const { field, order } = event;
  queryData.indicatorFiled = field;
  queryData.indicatorOrder = order;
};

let currentCompany = $ref({
  companyName: '',
  seqIndex: ''
});
const handleRes = (res: any) => {
  let _columns: any[] = [];
  let _units = {
    companyName: '单位'
  };
  if (queryData.pageNum == 1) {
    currentCompany.companyName = res?.currentCompanyData?.performanceSecurities?.securitiesName || '-';
    currentCompany.seqIndex = res?.currentNum || '-';
  }

  let max = { companyName: '最大值' };
  let min = { companyName: '最小值' };
  let mid = { companyName: '中位数' };
  let _data: any[] = [];

  if (res.comparisonData.indicators) {
    res.comparisonData.indicators.forEach((ind, iidx) => {
      _columns.push({
        title: ind.name,
        field: ind.code,
        width: 150,
        align: 'center',
        sortable: true,
        sortBy: ind.code,
        slots: {
          default: ({ row, rowIndex }) => {
            const showRemark = rowIndex > 4 && row[ind.code] && row[ind.code] !== '-' && (row[ind.code + 'Obj'].calcIndicatorRemark || row[ind.code + 'Obj'].contentDescription);
            if (traceSource.value && rowIndex > 4 && row[ind.code] !== '-' && row[ind.code + 'Obj'].fileUrl) {
              return (
                <a class={showRemark ? 'remark' : ''} onClick={() => openSourceDialog(row[ind.code + 'Obj'], showRemark)}>
                  {row[ind.code]}
                </a>
              );
            } else {
              return (
                <span class={showRemark ? 'remark' : ''} onClick={() => openSourceDialog(row[ind.code + 'Obj'], showRemark)}>
                  {row[ind.code]}
                </span>
              );
            }
          }
        }
      });
      _units[ind.code] = ind.unit;
      if (queryData.pageNum == 1) {
        currentCompany[ind.code] = res?.currentCompanyData?.indicatorInfo[iidx]?.indicatorDisplayValue || '-';
      }
      max[ind.code] = res?.statistics[0][iidx] || '-';
      min[ind.code] = res?.statistics[1][iidx] || '-';
      mid[ind.code] = res?.statistics[2][iidx] || '-';
    });
  }

  if (res.comparisonData.details) {
    _data = res.comparisonData.details.map((d, iidx) => {
      let left = {
        companyId: d?.performanceSecurities?.companyId || '',
        companyName: d?.performanceSecurities?.securitiesName || '',
        seqIndex: (queryData.pageNum - 1) * queryData.pageSize + iidx + 1
      };
      let right = {};
      d.indicatorInfo.forEach((indi, i) => {
        if (indi && indi?.indicatorDisplayValue) {
          right[_columns[i].field] = indi?.indicatorDisplayValue;
          right[_columns[i].field + 'Obj'] = indi;
        } else {
          right[_columns[i].field] = '-';
          right[_columns[i].field + 'Obj'] = {};
        }
      });
      return { ...left, ...right };
    });
    _data.unshift(_units, currentCompany, max, min, mid);
  }

  return {
    _columns,
    _data
  };
};

const openSourceDialog = (item, remark) => {
  if (remark || (item.indicatorDisplayValue && traceSource.value)) {
    item.year = item.statisticalPeriod;
    item.value = item.indicatorDisplayValue;
    actionSheetData.value = item;
    showActionsheet.value = true;
  }
};
</script>